package com.cortex.carambola.fetch;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

import com.cortex.carambola.utilities.MessagesLog;


public class FetchImages {

	private OnStateChanged onStateChanged;
	private int imagesNumberToFetching;
	private int imagesAmount;
	private List<Bitmap> images;

	private final static int TIME_OUT_CONNECTION = 5000;
	StartImagesThread startImagesThread;


	public FetchImages(){
		images = new ArrayList<Bitmap>();
	}
	public void startFetching(String url,int imagesNumberToFetching){
		if(isRunning() || (imagesAmount != 0 && imagesAmount == images.size())){
			return;
		}
		this.imagesNumberToFetching = imagesNumberToFetching;
		startImagesThread = new StartImagesThread();
		startImagesThread.execute(url);
	}
	public void cancelFetching(){
		if(startImagesThread !=  null){
			startImagesThread.cancel(true);
		}
	}
	public boolean isRunning() {
		return startImagesThread == null?false:startImagesThread.isRunning();
	}
	public void setOnStateChanged(OnStateChanged onStateChanged) {
		this.onStateChanged = onStateChanged;
	}
	public int getAmountImages(){
		return imagesAmount;
	}
	private class StartImagesThread extends AsyncTask<String, Bitmap, List<Bitmap>>{

		private Document doc;
		private Elements elementsImages;
		private boolean isRunning = false;

		@Override
		protected List<Bitmap> doInBackground(String... params) {

			try {
				//Connect to the website and get the html
				connectToUrl(params[0]);
				int amountContinueFetching = images.size() + imagesNumberToFetching;
				for (int i = images.size(); i < amountContinueFetching && i < imagesAmount; i++) {
					Element el = elementsImages.get(i);
					String src = el.absUrl("src");
					URL url = new URL(src);
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();   
					conn.setDoInput(true);   
					conn.connect();   
					InputStream is = conn.getInputStream();
					Bitmap bmImg = BitmapFactory.decodeStream(is); 
					onProgressUpdate(bmImg);
					images.add(bmImg);
				}

			} catch (IOException e) {
				String message = e.getMessage();
				Log.d(MessagesLog.APPLICATION_EXCEPTION,"" + message);
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.d(MessagesLog.APPLICATION,"" + "application finished download all images from web site.");
			return images;
		}
		@Override
		protected void onPreExecute() {
			isRunning = true;
			if(onStateChanged != null){
				onStateChanged.timeLoadStarted();
			}
		}
		@Override
		protected void onProgressUpdate(Bitmap... values) {
			if(onStateChanged != null){
				onStateChanged.downloadedData(values[0], images.size(), imagesAmount);
			}
		}
		@Override
		protected void onPostExecute(List<Bitmap> images) {
			isRunning = false;
			if(onStateChanged != null){
				onStateChanged.timeLoadFinished(images);
			}
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
			if(onStateChanged != null){
				onStateChanged.timeLoadCanceled("summary canceled");
			}
		}
		private void connectToUrl(String url) throws IOException{
			doc = Jsoup.connect(url).timeout(TIME_OUT_CONNECTION).get();
			elementsImages = doc.select("img[src~=(?i)\\.(png|jpe?g|gif)]");
			imagesAmount = elementsImages.size();
		}
		public boolean isRunning() {
			return isRunning;
		}

	}

	public interface OnStateChanged{
		void timeLoadStarted();
		void downloadedData(Bitmap image,int downloadNumber,int amount);
		void timeLoadFinished(List<Bitmap> images);
		void timeLoadCanceled(String message);
	}


}
